package org.llc.gof.structure.proxy.dynamic.basic1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author harvey
 */
public class DynamicProxy {
	
    private Object obj;
	
	private InvocationHandler handler;
	
	public DynamicProxy(Object subject){
		Class<? extends Object> clazz = subject.getClass();
		handler = new MyInvocationHandler(subject);
		this.obj = Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), handler);
	}  
	
	public Object execute(String methodName, Object...args){
		Object result = null;
		Class<?>[] c = new Class[args.length];
		int i=0;
		for(Object o : args){
			c[i] = o.getClass();
			i++;
		}
		try {
			Method method = this.obj.getClass().getMethod(methodName, c);
			result = method.invoke(this.obj, args);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
